import os
import logging
import re
import random
import cgi
import urllib

from waveapi import events
from waveapi import model
from waveapi import robot
from waveapi import document
from google.appengine.ext.webapp import template
from google.appengine.api import urlfetch
from google.appengine.ext import db
from google.appengine.api import users

class WaveUser(db.Model):
  name = db.StringProperty(required=True)
  waveId = db.StringProperty(required=True)
  mobile = db.PhoneNumberProperty()
  fixeline = db.PhoneNumberProperty()

def on_self_added(properties, context):
  """Invoked when any participants have been added/removed."""
  added = properties['participantsAdded']
  for p in added:
    if p == 'orangecallme@appspot.com':
      Setup(context)
      break
  
def on_submitted(properties, context):
  """  """
  delta = {}
  calletId = "none"
  callToId = "none"
  szblipId = properties['blipId']
  blip = context.GetBlipById(szblipId)
  doc = blip.GetDocument()
  gadget = blip.GetGadgetByUrl('http://orangecallme.appspot.com/assets/callme.xml')
  words = doc.GetText()
  if not gadget:
    logging.info('No gadget found. odd')
    return
  else:
    logging.info('Gadget found. yeah !')
    key = 'callerId'
    if hasattr(gadget, 'callerId'):
      callerId = gadget.get('callerId','')
    if hasattr(gadget, 'callToId'):
      callToId = gadget.get('callToId','')
    
    logging.debug("Caller ID : %s" % callerId)
    logging.debug("CallTo ID : %s" % callToId)
    #search Phone Numbers
    callerPhoneNumber = searchPhone(callerId)
    callToPhoneNumber = searchPhone(callToId)
    
    #url_to_fetch = "http://voicemashup.alpha.orange-api.net/call/createVoiceMashupCall.xml?id=534ca8a7aa9&to="+phone_number+"&url=" + voiceXML_URL 
    if callerPhoneNumber and callToPhoneNumber:
      url_to_fetch = "http://call.beta.orange-api.net/call/createCall.xml?id=534ca8a7aa9&from="+callerPhoneNumber+"&to="+callToPhoneNumber
      logging.debug("URL to play: %s" % url_to_fetch)
      result = urlfetch.fetch(url_to_fetch)
      delta = {}
      delta['callerId']=''
      delta['callToId']=''
      gadget.SubmitDelta(delta)
      doc.GadgetSubmitDelta(gadget,delta)
    

def searchPhone(waveId):
  logging.debug("Search for : %s" % waveId)
  if waveId == '':
    logging.debug("No waveId Passed")
    return ''
  else:
    query = db.GqlQuery("SELECT * FROM WaveUser WHERE waveId = :1",waveId)
    waver= query.get()
    if waver:
      logging.debug("Found a Waver : %s" % waver.name)
      callerphone = waver.fixeline
      logging.debug("Found a Phone : %s" % waver.fixeline)
      return callerphone
    else:
      logging.debug("No Waver Found")
      return ''
    

def Setup(context):
  blip = context.GetBlipById(context.GetRootWavelet().GetRootBlipId())
  if blip:
    """blip.GetDocument().SetText('Call me gadget !')"""
    blip.GetDocument().AppendElement(
        document.Gadget('http://orangecallme.appspot.com/assets/callme.xml'))


if __name__ == '__main__':
  logging.getLogger().setLevel(logging.DEBUG)
  dummy = robot.Robot('Orange Call Me', '1.0',
                      image_url='http://orangecallme.appspot.com/assets/icon.png',
                      profile_url='http://orangecallme.appspot.com/_wave/robot/profile')
  dummy.RegisterHandler(events.WAVELET_SELF_ADDED, on_self_added)
  dummy.RegisterHandler(events.BLIP_SUBMITTED, on_submitted)
  dummy.RegisterHandler(events.BLIP_TIMESTAMP_CHANGED, on_submitted)
  dummy.RegisterHandler(events.BLIP_VERSION_CHANGED, on_submitted)
  dummy.Run(debug=True)

